<?php

namespace app\v1\controller;
use support\Request;
use app\model\Util;
use app\model\BizGoodsModel;
use app\model\BizGoodsImageModel;
use app\model\BizGoodsOrderModel;
use app\model\CardUserModel;
use app\model\UserModel;
use EasyWeChat\Factory;
use support\Log;
use app\model\BizGoodsTicketModel;
use app\model\BizModel;
use app\model\PayPingModel;
use app\model\CardItemModel;
use support\Db;

class BizGoodsController {
    
    public function index(Request $request){
        $id = $request->get('id');

        $query = BizGoodsModel::query();
        $data = $query->whereNull('deleted_at')
            ->where('biz_id','=',$id)->orderBy('id', 'desc')
            ->get();

        foreach($data as &$item){
            $item['image_url'] = Util::pathToUrl($item['image']);
        }

        return json([
            'code' => 1,
            'data' => $data,
        ]);
    }

    public function search(Request $request){
        try {
            $keyword = $request->get('keyword');
            $page = $request->get('page', 1);
            $pageSize = $request->get('pageSize', 10);

            if (empty($keyword)) {
                throw new \Exception('搜索关键词不能为空');
            }
    
            $query = BizGoodsModel::query();
            $query->whereNull('deleted_at')
                ->where('title', 'like', '%' . $keyword . '%');

            $total = $query->count();
            $data = $query->orderBy('id', 'desc')
                ->limit($pageSize)
                ->offset(($page - 1) * $pageSize)
                ->get();

            foreach($data as &$item){
                $item['image_url'] = Util::pathToUrl($item['image']);
                $item['price'] = round($item['price'], 2);

                $biz = BizModel::find($item['biz_id']);
                $item['biz_name'] = $biz['name'];
            }

            return json([
                'code' => 1,
                'data' => $data,
                'total' => $total,
                'msg' => '搜索成功'
            ]);
        }catch(\Exception $e){
            return json([
                'code' => 0,
                'data' => null,
                'msg' => $e->getMessage()
            ]);
        }
    }

    public function detail(Request $request){
        $id = $request->get('id');

        $data = BizGoodsModel::find($id);
        $data['image_url'] = Util::pathToUrl($data['image']);

        $goodsImages = [
            [
                'image_url' => $data['image_url'],
            ]
        ];

        // 轮播
        $images = BizGoodsImageModel::where('goods_id','=', $id)
            ->where('type','=','banner')->get();
        foreach($images as $item){
            $goodsImages[] = [
                'image_url' => Util::pathToUrl($item['path']),
            ];
        }
        $data['images'] = $goodsImages;

        $data['price'] = round($data['price'], 2);
        $data['market_price'] = round($data['market_price'], 2);

        // 详情图片
        $detailImages = BizGoodsImageModel::where('goods_id','=', $id)
            ->where('type','=','detail')->get();
        foreach($detailImages as $item){
            $data['detail_images'][] = [
                'image_url' => Util::pathToUrl($item['path']),
            ];
        }

        $data['comment_total'] = PayPingModel::where('goods_id','=', $id)
            ->where('type','=','biz-order')->count();

        // 获得所属商家信息
        $biz = BizModel::find($data['biz_id']);
        $data['biz_name'] = $biz['name'];
        
        return json([
            'code' => 1,
            'data' => $data,
        ]);
    }

    /**
     * 生成消费订单
     * @param \support\Request $request
     * @throws \Exception
     * @return \support\Response
     */
    public function buy(Request $request){
        try {
            $input = $request->post();
            $user = $request->userLogin;

            // 参数验证
            if (empty($input['id'])) {
                throw new \Exception('商品ID不能为空');
            }
            if (empty($input['quantity']) || $input['quantity'] <= 0) {
                throw new \Exception('购买数量必须大于0');
            }

            $goods = BizGoodsModel::find($input['id']);
            if (empty($goods)) {
                throw new \Exception('商品不存在');
            }

            $totalPrice = $goods->price * $input['quantity'];
            $useScore = (float)($input['use_score'] ?? 0);
            $useCardScore = (float)($input['use_card_score'] ?? 0);
            $selectedCards = $input['selected_cards'] ?? [];

            // 验证云豆使用量
            if ($useScore > 0) {
                if ($useScore > $user->score) {
                    throw new \Exception('云豆余额不足');
                }
            }

            // 验证福利卡使用量
            if ($useCardScore > 0 && !empty($selectedCards)) {
                $totalCardScore = 0;
                foreach ($selectedCards as $cardData) {
                    $cardId = $cardData['card_id'] ?? 0;
                    // 查询用户卡片信息
                    $cardUser = CardUserModel::find($cardData['card_id']);
                    
                    if (!$cardUser) {
                        throw new \Exception('卡片不存在或已失效');
                    }
                    
                    // 检查卡片是否过期
                    if ($cardUser->expired_at > 0 && $cardUser->expired_at < time()) {
                        throw new \Exception('卡片已过期');
                    }
                    
                    $totalCardScore += $cardUser->score;
                }
                
                if ($useCardScore > $totalCardScore) {
                    throw new \Exception('福利卡云豆余额不足');
                }
            }

            // 计算实际支付金额
            $totalUseScore = $useScore + $useCardScore;
            $remainMoney = round(($totalPrice - $totalUseScore),2);
            
            if ($remainMoney < 0) {
                throw new \Exception('支付金额计算错误');
            }

            // 创建订单
            $order = new BizGoodsOrderModel();
            $order->user_id = $user->id;
            $order->biz_goods_id = $input['id'];
            $order->quantity = $input['quantity'];
            $order->pay_money = $totalPrice;
            $order->price = $goods->price;
            $order->money = $remainMoney;
            $order->score = $useScore;
            $order->card_score = $useCardScore;
            $order->card_score_data = json_encode($selectedCards);
            $order->status = $remainMoney > 0 ? 'unpay' : 'pay';
            $order->created_at = time();
            $order->updated_at = time();
            $order->biz_id = $goods->biz_id;
            $order->phone = $user->phone;
            $order->expired_at = time() + (30 * 24 * 3600); // 30天后过期
            $order->save();

            $baseTradeNo = 'B'.date('ymd').str_pad($order->id, 8, '0', STR_PAD_LEFT);
            $order->trade_no = $baseTradeNo.substr(md5($baseTradeNo), 0, 2);
            $out_trade_no = 'bizo-' . $order->id . "-" . rand(100000, 999999);
            $order->out_trade_no = $out_trade_no;
            $order->save();

            // 如果无需微信支付，直接完成订单并扣除余额
            if ($remainMoney <= 0) {
                // 扣除用户云豆余额
                if ($useScore > 0) {
                    $user->score = round($user->score - $useScore, 2);
                    $user->save();
                }

                // 扣除福利卡云豆余额
                if ($useCardScore > 0 && !empty($selectedCards)) {
                    foreach ($selectedCards as $cardData) {
                        $cardId = $cardData['card_id'] ?? 0;
                        $cardUser = CardUserModel::find($cardId);
                        
                        if ($cardUser) {
                            $cardUseScore = min($cardUser->score, (float)($cardData['use_score'] ?? 0));
                            $cardUser->score = round($cardUser->score - $cardUseScore, 2);
                            $cardUser->use_score = round($cardUser->use_score + $cardUseScore, 2);
                            $cardUser->save();
                        }
                    }
                }

                $order->status = 'pay';
                $order->paid_at = time();
                $order->confirm_at = 0;
                $order->save();
                
                // 生成核销码
                try {
                    $tickets = BizGoodsTicketModel::generateTickets($order);
                    BizGoodsTicketModel::batchSaveTickets($tickets);
                } catch (\Exception $e) {
                    Log::error('生成核销码失败: ' . $e->getMessage());
                    // 不中断支付流程，只记录错误
                }
                
                return json([
                    'code' => 1,
                    'data' => [
                        'order_id' => $order->id,
                        'config' => null,
                        'remain_money' => 0,
                        'message' => '支付成功'
                    ],
                    'msg' => '购买成功'
                ]);
            }

            // 需要微信支付 - 不在这里扣除云豆和福利卡余额，等支付回调时扣除
            $config = config('wechat.mini_app');
            $payment = Factory::payment($config);
            $jssdk = $payment->jssdk;

            $params = [
                'body' => $goods->title,
                'out_trade_no' => $out_trade_no,
                'total_fee' => $remainMoney * 100,
                'notify_url' => config('site.site_url')."/v1/biz-goods/notify",
                'trade_type' => 'JSAPI',
                'openid' => $user->open_id,
            ];


            $result = $payment->order->unify($params);
            if($result['return_code'] != 'SUCCESS'){
                throw new \Exception($result['return_msg']);
            }

            if($result['result_code'] != 'SUCCESS'){
                throw new \Exception($result['err_code_des']);
            }

            $config = $jssdk->bridgeConfig($result['prepay_id'], false);

            return json([
                'code' => 1,
                'data' => [
                    'order_id' => $order->id,
                    'config' => $config,
                    'remain_money' => $remainMoney,
                    'result' => $result,
                ],
                'msg' => '订单创建成功'
            ]);
            
        } catch (\Exception $e) {
            return json([
                'code' => 0,
                'data' => null,
                'msg' => $e->getMessage()
            ]);
        }
    }

    public function notify(Request $request){
        try {
            $config = config('wechat.mini_app');
            $payment = Factory::payment($config);
            
            $response = $payment->handlePaidNotify(function ($message, $fail) {
                // 查询支付记录
                $outTradeNo = $message['out_trade_no'];
                $orderId = (int)explode('-', $outTradeNo)[1];
                
                $order = BizGoodsOrderModel::find($orderId);
                if (!$order) {
                    return $fail('订单不存在');
                }

                // 检查支付状态
                if ($order->status == 'pay') {
                    return true; // 已经处理过
                }

                // 验证支付金额
                $expectedAmount = (int)($order->money * 100);
                if ($message['total_fee'] != $expectedAmount) {
                    return $fail('支付金额不匹配');
                }

                // 更新支付记录
                $order->status = 'pay';
                $order->paid_at = time();
                $order->transaction_id = $message['transaction_id'];
                $order->save();

                // 扣除用户云豆余额
                if ($order->score > 0) {
                    $user = UserModel::find($order->user_id);
                    if ($user) {
                        $user->score = round($user->score - $order->score, 2);
                        $user->save();
                    }
                }

                // 扣除福利卡云豆余额
                if ($order->card_score > 0 && !empty($order->card_score_data)) {
                    $selectedCards = json_decode($order->card_score_data, true);
                    foreach ($selectedCards as $cardData) {
                        $cardId = $cardData['card_id'] ?? 0;
                        $cardUser = CardUserModel::find($cardId);
                        
                        if ($cardUser) {
                            $cardUseScore = min($cardUser->score, (float)($cardData['use_score'] ?? 0));
                            $cardUser->score = round($cardUser->score - $cardUseScore, 2);
                            $cardUser->save();

                            $cardItem = CardItemModel::find($cardUser->card_item_id);
                            if ($cardItem) {
                                $cardItem->use_score = round($cardItem->use_score + $cardUseScore, 2);
                                $cardItem->save();
                            }
                        }
                    }
                }

                // 生成核销码
                try {
                    $tickets = BizGoodsTicketModel::generateTickets($order);
                    BizGoodsTicketModel::batchSaveTickets($tickets);
                } catch (\Exception $e) {
                    Log::error('生成核销码失败: ' . $e->getMessage());
                    // 不中断支付流程，只记录错误
                }

                return true;
            });

            return $response;
        } catch (\Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 获取最近商品订单记录
     * @param Request $request
     * @return \support\Response
     */
    public function recentOrders(Request $request)
    {
        try {
            $goodsId = $request->get('goods_id');

            $query = BizGoodsOrderModel::whereNull('deleted_at');

            // 优先显示当前商品的订单（最多30条）
            $currentGoodsOrders = $query->where('biz_goods_id', $goodsId)
                ->orderBy('created_at', 'desc')
                ->limit(30)
                ->get();

            // 获取其他商品的订单（最多20条，确保总数不超过50条）
            $remainingLimit = 50 - count($currentGoodsOrders);
            $otherGoodsOrders = $query->where('biz_goods_id', '!=', $goodsId)
                ->orderBy('created_at', 'desc')
                ->limit($remainingLimit)
                ->get();

            // 合并订单列表，当前商品订单在前
            $allOrders = $currentGoodsOrders->merge($otherGoodsOrders);

            $orders = [];
            foreach ($allOrders as $order) {
                // 获取商品信息
                $orderGoods = BizGoodsModel::find($order->biz_goods_id);
                $user = UserModel::find($order->user_id);
                
                $orderData = [
                    'id' => $order->id,
                    'biz_goods_id' => $order->biz_goods_id,
                    'quantity' => $order->quantity,
                    'status' => $order->status,
                    'status_text' => $this->getOrderStatusText($order->status),
                    'created_at' => human_time($order->created_at),
                    'is_current_goods' => $order->biz_goods_id == $goodsId,
                    'user_name' => $user->nickname,
                    'user_phone' => $user->phone,
                ];

                // 添加商品信息
                if ($orderGoods) {
                    $orderData['goods_title'] = $orderGoods->title;
                    $orderData['goods_image'] = Util::pathToUrl($orderGoods->image);
                    $orderData['goods_price'] = $orderGoods->price;
                } else {
                    $orderData['goods_title'] = '商品已删除';
                    $orderData['goods_image'] = '';
                    $orderData['goods_price'] = 0;
                }

                $orders[] = $orderData;
            }

            return json([
                'code' => 1,
                'data' => [
                    'list' => $orders,
                    'total' => count($orders),
                    'current_goods_count' => count($currentGoodsOrders),
                    'other_goods_count' => count($otherGoodsOrders)
                ],
                'msg' => '获取最近订单记录成功'
            ]);

        } catch (\Exception $e) {
            return json([
                'code' => 0,
                'data' => null,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 获取订单状态文本
     * @param string $status
     * @return string
     */
    private function getOrderStatusText($status)
    {
        $statusMap = [
            'unpay' => '待支付',
            'pay' => '已支付'
        ];

        return $statusMap[$status] ?? '未知状态';
    }

    /**
     * 获取消费订单列表
     * @param Request $request
     * @return \support\Response
     */
    public function getOrderList(Request $request)
    {
        try {
            $user = $request->userLogin;
            $page = intval($request->get('page', 1));
            $limit = intval($request->get('limit', 10));
            $range = $request->get('range', 'all');
            $keyword = $request->get('keyword', '');
            
            // 参数验证
            if ($page < 1) {
                $page = 1;
            }
            if ($limit < 1 || $limit > 50) {
                $limit = 10;
            }

            $offset = ($page - 1) * $limit;

            // 查询用户的消费订单
            $query = BizGoodsOrderModel::with(['bizGoods', 'biz'])
                ->where('user_id', $user->id)
                ->where('hide_at', '=',0)
                ->whereNull('deleted_at')
                ->orderBy('created_at', 'desc');

            if($range == 'all'){
                // 所有订单，不需要额外限制
            }else if($range == 'unpay'){
                $query->where('status', '=', 'unpay');
            }else if($range == 'un-used'){
                $query->where('status', '=', 'pay')->where('confirm_total','<',DB::raw('quantity - refund_total'));
            }else if($range == 'refund'){
                $query->where('status', '=', 'pay')->where('refund_total','>',0);
            }else if($range == 'done'){
                $query->where('status', '=', 'done');
            }

            if(!empty($keyword)){
                $query->whereHas('bizGoods', function($q) use ($keyword) {
                    $q->where('title', 'like', '%'.$keyword.'%');
                });
            }

            // 获取总数
            $total = $query->count();

            // 获取分页数据
            $orders = $query->offset($offset)->limit($limit)->get();

            $orderList = [];
            foreach ($orders as $order) {
                $orderData = [
                    'id' => $order->id,
                    'biz_goods_id' => $order->biz_goods_id,
                    'quantity' => $order->quantity,
                    'price' => round($order->price, 2), // 单价
                    'money' => round($order->money, 2), // 差价金额
                    'pay_money' => round($order->pay_money, 2), // 实付金额
                    'status' => $order->status,
                    'status_text' => $this->getOrderStatusText($order->status),
                    'created_at' => $order->created_at,
                    'created_at_text' => date('Y-m-d H:i:s', $order->created_at),
                    'paid_at' => $order->paid_at,
                    'paid_at_text' => $order->paid_at ? date('Y-m-d H:i:s', $order->paid_at) : '',
                    'transaction_id' => $order->transaction_id,
                    'out_trade_no' => $order->out_trade_no,
                    'expired_at' => $order->expired_at,
                    'ping_id' => $order->ping_id,
                    'expired_at_text' => $order->expired_at ? date('Y-m-d', $order->expired_at) : '',
                ];

                // 添加商家信息
                if ($order->biz) {
                    $orderData['biz_name'] = $order->biz->name;
                    $orderData['biz_id'] = $order->biz->id;
                    $orderData['biz_image'] = Util::pathToUrl($order->biz->image);
                } else {
                    $orderData['biz_name'] = '商家已删除';
                    $orderData['biz_id'] = 0;
                    $orderData['biz_image'] = '';
                }

                // 添加商品信息
                if ($order->bizGoods) {
                    $orderData['goods_title'] = $order->bizGoods->title;
                    $orderData['goods_image'] = Util::pathToUrl($order->bizGoods->image);
                    $orderData['goods_price'] = round($order->bizGoods->price, 2);
                } else {
                    $orderData['goods_title'] = '商品已删除';
                    $orderData['goods_image'] = '';
                    $orderData['goods_price'] = 0;
                }

                $orderList[] = $orderData;
            }

            // 计算是否有更多数据
            $hasMore = ($offset + $limit) < $total;

            return json([
                'code' => 1,
                'data' => [
                    'list' => $orderList,
                    'total' => $total,
                    'page' => $page,
                    'limit' => $limit,
                    'has_more' => $hasMore
                ],
                'msg' => '获取消费订单列表成功'
            ]);

        } catch (\Exception $e) {
            return json([
                'code' => 0,
                'data' => null,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 获取所有商家商品列表
     * @param Request $request
     * @return \support\Response
     */
    public function getAllGoodsList(Request $request)
    {
        try {
            $page = intval($request->get('page', 1));
            $limit = intval($request->get('limit', 10));
            
            // 参数验证
            if ($page < 1) {
                throw new \Exception('页码必须大于0');
            }
            if ($limit < 1 || $limit > 50) {
                throw new \Exception('每页数量必须在1-50之间');
            }

            $offset = ($page - 1) * $limit;

            // 查询所有商品，包含商家信息
            $query = BizGoodsModel::with(['biz'])
                ->whereNull('deleted_at')
                ->orderBy('id', 'desc');

            // 获取总数
            $total = $query->count();

            // 获取分页数据
            $goodsList = $query->offset($offset)->limit($limit)->get();

            $list = [];
            foreach ($goodsList as $goods) {
                // 获取销量（已支付的订单数量）
                $salesCount = BizGoodsOrderModel::where('biz_goods_id', $goods->id)
                    ->where('status', 'pay')
                    ->whereNull('deleted_at')
                    ->sum('quantity');

                $goodsData = [
                    'id' => $goods->id,
                    'title' => $goods->title,
                    'image_url' => Util::pathToUrl($goods->image),
                    'price' => round($goods->price, 2),
                    'market_price' => round($goods->market_price, 2),
                    'sales_count' => $salesCount,
                    'created_at' => $goods->created_at,
                    'created_at_text' => date('Y-m-d H:i:s', $goods->created_at),
                ];

                // 添加商家信息
                if ($goods->biz) {
                    $goodsData['biz_id'] = $goods->biz->id;
                    $goodsData['biz_name'] = $goods->biz->name;
                    $goodsData['biz_image'] = Util::pathToUrl($goods->biz->image);
                } else {
                    $goodsData['biz_id'] = 0;
                    $goodsData['biz_name'] = '商家已删除';
                    $goodsData['biz_image'] = '';
                }

                $list[] = $goodsData;
            }

            // 计算是否有更多数据
            $hasMore = ($offset + $limit) < $total;

            return json([
                'code' => 1,
                'data' => [
                    'list' => $list,
                    'total' => $total,
                    'page' => $page,
                    'limit' => $limit,
                    'has_more' => $hasMore
                ],
                'msg' => '获取商品列表成功'
            ]);

        } catch (\Exception $e) {
            return json([
                'code' => 0,
                'data' => null,
                'msg' => $e->getMessage()
            ]);
        }
    }

    public function pings(Request $request){
        $id = $request->get('id');
        $page = max(1, intval($request->get('page', 1)));
        $limit = max(1, intval($request->get('limit', 10)));
        $offset = ($page - 1) * $limit;

        $query = PayPingModel::where('goods_id', '=', $id)
            ->where('type', '=', 'biz-order');

        $total = $query->count();

        $data = $query->orderBy('id', 'desc')
            ->offset($offset)
            ->limit($limit)
            ->get();

        foreach($data as &$item){
            $item['images'] = $item->doImages();
            $item['user'] = UserModel::userCache($item->user_id);
            $item['created_at'] = human_time(strtotime($item->created_at));
        }

        $hasMore = ($offset + $limit) < $total;

        return json([
            'code' => 1,
            'data' => [
                'list' => $data,
                'total' => $total,
                'page' => $page,
                'limit' => $limit,
                'has_more' => $hasMore
            ],
        ]);
    }
}
